package com.ft.adbix.core.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import com.ft.adbix.utils.AdLogUtils;
import com.ft.adbix.utils.http.HttpHelper;
import com.ft.adbix.utils.http.listener.SimpleHttpListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DelayedRequestService extends Service {
    private static final String TAG = "com.ft.adbix.core.service.DelayedRequestService";
    private static final String ACTION_SCHEDULE_REQUEST = "com.example.SCHEDULE_REQUEST";
    private static final String EXTRA_DELAY_SECONDS = "delay_seconds";
    private static final String EXTRA_URL = "url";
    private static final String EXTRA_REQUEST_ID = "request_id";

    private Handler handler;
    private Map<String, Runnable> pendingRequests; // 存储待执行的请求

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler(Looper.getMainLooper());
        pendingRequests = new HashMap<>();
        AdLogUtils.d("DelayedRequestService created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && ACTION_SCHEDULE_REQUEST.equals(intent.getAction())) {
            handleScheduleRequest(intent);
        }

        // 返回START_STICKY使服务在被杀死后自动重启
        return START_STICKY;
    }

    private boolean checkIfInBackground() {
        boolean isInBackground = false;
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.processName.equals(getPackageName())){
                AdLogUtils.i("process info : name = "+processInfo.processName+"--importance = "+processInfo.importance);
                if (processInfo.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    isInBackground = true;
                    break;
                }
            }
        }
        return isInBackground;
    }

    private void handleScheduleRequest(Intent intent) {
        int delaySeconds = intent.getIntExtra(EXTRA_DELAY_SECONDS, 10);
        String url = intent.getStringExtra(EXTRA_URL);
        String requestId = intent.getStringExtra(EXTRA_REQUEST_ID);

        if (url == null) {
            return;
        }

        if (requestId == null) {
            requestId = "request_" + System.currentTimeMillis(); // 生成默认ID
        }

        // 如果已存在相同ID的请求，先取消它
        cancelPendingRequest(requestId);

        // 创建延迟任务
        final String finalUrl = url;
        final String finalRequestId = requestId;

        Runnable delayedRunnable = new Runnable() {
            @Override
            public void run() {
                AdLogUtils.d("Executing delayed request: " + finalRequestId);
                if (checkIfInBackground()) {
                    AdLogUtils.d("isInBackground");
                    sendNetworkRequest(finalUrl, finalRequestId);
                }
                // 任务完成后从待执行列表中移除
                pendingRequests.remove(finalRequestId);
            }
        };

        // 添加到待执行列表
        pendingRequests.put(requestId, delayedRunnable);

        // 安排延迟执行
        handler.postDelayed(delayedRunnable, delaySeconds * 1000L);
    }

    private void cancelPendingRequest(String requestId) {
        Runnable existingRunnable = pendingRequests.get(requestId);
        if (existingRunnable != null) {
            handler.removeCallbacks(existingRunnable);
            pendingRequests.remove(requestId);
        }
    }

    private void sendNetworkRequest(String url, String requestId) {
        HttpHelper.post(url, null, new SimpleHttpListener() {
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清理所有待执行的任务
        if (handler != null) {
            for (Runnable runnable : pendingRequests.values()) {
                handler.removeCallbacks(runnable);
            }
            pendingRequests.clear();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 提供静态方法供外部调用
    public static void scheduleRequest(Context context, String url, int delaySeconds, String requestId) {
        Intent intent = new Intent(context, DelayedRequestService.class);
        intent.setAction(ACTION_SCHEDULE_REQUEST);
        intent.putExtra(EXTRA_URL, url);
        intent.putExtra(EXTRA_DELAY_SECONDS, delaySeconds);
        intent.putExtra(EXTRA_REQUEST_ID, requestId);
        context.startService(intent);
    }

    public static void scheduleRequest(Context context, String url, int delaySeconds) {
        scheduleRequest(context, url, delaySeconds, null);
    }

//    public static void scheduleRequest(Context context, int delaySeconds) {
//        scheduleRequest(context, null, delaySeconds, null);
//    }
}